package com.cmuis.goodguide;

import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.provider.SearchRecentSuggestions;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

/*
 * This history activity / page will hold and list the users previously viewed items
 * for later viewing.
 */
public class History extends Activity {
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.history);
		TextView text = (TextView)findViewById(R.id.history_text);
		
		//Pull all of the Persistent Data out of internal storage
		SharedPreferences prefs = this.getSharedPreferences("prefs", MODE_WORLD_READABLE);
		
		// Get a map of all the items in history
		Map<String, ?> history = prefs.getAll();
		
		// Get all the product keys
		Set<String> historyKeys = history.keySet();
		
		// Iterate through the keys and return the product IDs
		Iterator<String> historyItr = historyKeys.iterator();
		if (history.isEmpty())
		{
		text.setText("No Search History found.");
		}
		else {
		//This is the list that stores all the data for each item in the displayed list
		List<HashMap<String, String>> displayList = new ArrayList<HashMap<String, String>>();
		System.out.println(historyKeys.toString());
		while (historyItr.hasNext())
		{
			HashMap<String, String> map = new HashMap<String, String>();
			Product historyItem = openConnection((String)history.get(historyItr.next()));
			try {
			map.put("product", historyItem.getName().toString());
			map.put("ID", historyItem.getId().toString());
			displayList.add(map);
			}
			catch (NullPointerException e){
				
			}
		}
		ListView list = (ListView) findViewById(R.id.history_view);
		
		SimpleAdapter mSchedule = new SimpleAdapter(History.this,
				displayList, R.layout.history_rows, new String[] { "product", "ID" },
				new int[] { R.id.history_txt, R.id.history_id});

		list.setAdapter(mSchedule);
		list.setTextFilterEnabled(true); // users can press a letter and filter
											// results by pressing a letter
		list.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Intent itemIntent = new Intent(view.getContext(),
						DetailsPage.class);
				Bundle b = new Bundle();
				 String tmp = ((TextView) view.findViewById(R.id.history_id)).getText().toString();
				b.putString("productID", tmp);
				b.putString("productUPC", null);
				itemIntent.putExtras(b);
				startActivity(itemIntent);
			}
		});
	}
	}

	/*
	 * Talks with the Goodguide API to get XML information, then parses the
	 * info.
	 */
	protected Product openConnection(String id) {
		try {
			URL url = new URL(
					"http://api.goodguide.com/"
							+ "search.xml?api_key=chm22jq6d5f5ytnnnfwan726&api_version=1.0&"
							+ "api_format=simple&id=" + id);

			SAXParserFactory spf = SAXParserFactory.newInstance();
			SAXParser sp = spf.newSAXParser();

			XMLReader xr = sp.getXMLReader();

			ProductParser handler = new ProductParser();
			xr.setContentHandler(handler);

			xr.parse(new InputSource(url.openStream()));

			return handler.getProduct();

		} catch (Exception e) {
			return null;
		}

	}
	// Sets menu functionality
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.history_menu, menu);
		return true;
	}

	// Standard menu items like elsewhere in the application.
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.search:
			Intent i = new Intent(this, goodguide.class);
			startActivity(i);
			return true;
		case R.id.barcode_scanner:
			Intent j = new Intent(this, barcodescanner.class);
			startActivity(j);
			return true;
		case R.id.info:
			Intent q = new Intent(this, InfoPage.class);
			startActivity(q);
			return true;
		case R.id.clear_history:
			try {
				new AlertDialog.Builder(History.this)
						.setIcon(android.R.drawable.ic_dialog_alert)
						.setTitle(R.string.clear_history_title)
						.setMessage(R.string.clear_history)
						.setPositiveButton(
								R.string.confirm_clear_query,
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(
											DialogInterface dialog,
											int which) {
										SharedPreferences prefs = (History.this).getSharedPreferences("prefs", MODE_WORLD_READABLE);
										Editor edit = prefs.edit();
										edit.clear();
										edit.commit();
										Intent k = new Intent(History.this,goodguide.class);
										startActivity(k);
										finish();
									}
								})
						.setNegativeButton(R.string.reject_clear_query,
								null).show();

			} catch (Exception e) {

			}

		default:
			return super.onOptionsItemSelected(item);
		}
	}
}